iOS 键盘监听处理遮挡控件问题

键盘监听处理遮挡控件问题

1
2
3
4
5
6
7
8
9
10
11
12
#pragma mark - 键盘处理
#pragma mark 监听系统发出的键盘通知
- (void)addKeyboardNote {

NSNotificationCenter *center = [NSNotificationCenter defaultCenter];

// 1.显示键盘
[center addObserver:self selector:@selector(keyboardChange:) name:UIKeyboardWillShowNotification object:nil];

// 2.隐藏键盘
[center addObserver:self selector:@selector(keyboardChange:) name:UIKeyboardWillHideNotification object:nil];
}
  • 处理方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
- (void)keyboardChange:(NSNotification *)note {

NSDictionary *userInfo = note.userInfo;
NSTimeInterval duration;
CGRect keyboardF;

[[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
[[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] getValue:&keyboardF];

if (duration <= 0.0) {
duration = 0.25;
}

//取得当前聚焦文本框最下面的Y值
UITextField *field = [self.view viewWithTag:1];
CGFloat maxY = CGRectGetMaxY(field.frame) + 5;

[UIView animateWithDuration:duration animations:^{
if (maxY > CGRectGetMidY(keyboardF)) { //挡住了
self.view.transform = CGAffineTransformMakeTranslation(0, - (maxY - CGRectGetMidY(keyboardF) ));
} else { // 没有挡住
self.view.transform = CGAffineTransformIdentity;
}
}];
}
  • 销毁处理
1
2
3
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
-------------本文结束感谢阅读-------------